/***************************************************************************
 *   Copyright (C) 2010 by Peter Hatina                                    *
 *   email: phatina (at) gmail.com                                         *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License           *
 *   version 2.1 as published by the Free Software Foundation              *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Lesser General Public License for more details.                   *
 *   http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.               *
 ***************************************************************************/

#include "settingsdialog.h"
#include "settings.h"
#include "common.h"
#if (defined(Q_OS_WIN32) && (WINVER >= 0x0600))
#  include "powerscheme.h"
#endif
#include <QFileDialog>
#include <QMessageBox>
#include <QDirModel>

SettingsDialog::SettingsDialog(QWidget *parent):
    QDialog(parent),
    m_tab_widget(new TabWidget),
    m_completer(new QCompleter(this))
{
    // setup gui widgets
    setupUi(this);
#ifndef USE_LOGGING
    m_chk_log->setVisible(false);
    m_chk_log->setVisible(false);
    m_txt_log_file->setVisible(false);
    m_txt_log_file->setVisible(false);
    m_btn_browse->setVisible(false);
#endif

    // add tab widget, containing all the actions
    m_action_layout->addWidget(m_tab_widget.data(), 0, 0, 1, 3);

    m_completer->setModel(new QDirModel(m_completer.data()));
    m_txt_log_file->setCompleter(m_completer.data());
    connect(m_txt_log_file, SIGNAL(textChanged(const QString &)),
            this, SLOT(logChanged(const QString &)));

#if (defined(Q_OS_WIN32) && (WINVER >= 0x0600))
    m_use_schemes = true;
    connect(m_rd_min_power, SIGNAL(clicked()), this, SLOT(schemeChanged()));
    connect(m_rd_max_power, SIGNAL(clicked()), this, SLOT(schemeChanged()));
    connect(m_rd_balanced, SIGNAL(clicked()), this, SLOT(schemeChanged()));
#endif

#if (!defined(Q_OS_WIN32) || (WINVER < 0x0600))
    m_lst_pages->item(2)->setHidden(true);
#endif

    // widget connections
    connect(m_btn_ok, SIGNAL(clicked()), this, SLOT(okClicked()));
    connect(m_btn_apply, SIGNAL(clicked()), this, SLOT(saveSettings()));
    connect(m_btn_browse, SIGNAL(clicked()), this, SLOT(browseClicked()));
}

SettingsDialog::~SettingsDialog()
{
}

void SettingsDialog::show()
{
    loadSettings();
    m_lst_pages->setCurrentRow(0);
    m_scheme_changed = false;
    QDialog::show();
}

void SettingsDialog::saveSettings()
{
    // save all the actions
    Settings *settings = Settings::instance();
    settings->actionsClear();
    const int cnt = m_tab_widget->count();
    for (int i = 0; i < cnt; i++)
    {
        Action action;
        TabWidgetItem *item = static_cast <TabWidgetItem *> (m_tab_widget->widget(i));
        action.setType(item->getType());
        action.setAttr(item->getText());
        action.setLevel(item->getLevel());

        if (action.type() != Action::NOTHING)
            settings->actionsAdd(action);
    }

    // save application settings
#ifdef USE_LOGGING
    settings->setLogging(m_chk_log->isChecked());
    settings->setLogFile(m_txt_log_file->text());
#endif
    settings->setRunAtStartupGlobal(m_chk_run->isChecked() && m_rd_global->isChecked());
    settings->setRunAtStartCurrent(m_chk_run->isChecked() && m_rd_current->isChecked());
    settings->setUpdateInterval(m_spn_interval->value());

#if (defined(Q_OS_WIN32) && (WINVER >= 0x0600))
    // change power scheme
    if (m_use_schemes && m_scheme_changed)
    {
        PowerScheme sch;
        if (sch.powrProfLoaded())
        {
            QMessageBox msg;
            msg.setText("zmena rezimu");
            msg.exec();

            if (m_rd_min_power->isChecked())
                sch.setMinPower();
            else if (m_rd_max_power->isChecked())
                sch.setMaxPower();
            else
                sch.setBalanced();
        }
    }
#endif

    emit newConfiguration();
}

void SettingsDialog::loadSettings()
{
    // load settings
    Settings *settings = Settings::instance();

    // add new tabs with necessary content
    m_tab_widget->delTabs();
    const int cnt = settings->actionsCount();
    for (int i = 0; i < cnt; i++)
        m_tab_widget->addTab(settings->operator [](i));

    if (m_tab_widget->count() == 0)
        m_tab_widget->addTab();

    // set the first tab, to be active
    m_tab_widget->setCurrentIndex(0);

    // fill general settings widgets
#ifdef USE_LOGGING
    m_chk_log->setChecked(settings->log());
    m_chk_log->setVisible(settings->logEnabled());
    m_txt_log_file->setText(settings->logFile());
    m_txt_log_file->setVisible(settings->logEnabled());
    m_btn_browse->setVisible(settings.logEnabled());
#endif
    m_chk_run->setChecked(settings->runAtStartUpCurrent() || settings->runAtStartUpGlobal());
    m_rd_global->setChecked(settings->runAtStartUpGlobal());
    m_rd_current->setChecked(settings->runAtStartUpCurrent());
    m_spn_interval->setValue(settings->updateInterval());
}

#if (defined(Q_OS_WIN32) && (WINVER >= 0x0600))
void SettingsDialog::setMinPower(bool s)
{
    m_rd_min_power->setChecked(s);
    m_scheme_changed = false;
}

void SettingsDialog::setMaxPower(bool s)
{
    m_rd_max_power->setChecked(s);
    m_scheme_changed = false;
}

void SettingsDialog::setBalanced(bool s)
{
    m_rd_balanced->setChecked(s);
    m_scheme_changed = false;
}

void SettingsDialog::schemeChanged()
{
    m_scheme_changed = true;
}

void SettingsDialog::setUseSchemes(bool u)
{
    m_use_schemes = u;
    m_lst_pages->item(2)->setHidden(!u);
}

#endif

void SettingsDialog::okClicked()
{
    saveSettings();
    close();
}

void SettingsDialog::browseClicked()
{
    QFileDialog dialog(this);
    dialog.setConfirmOverwrite(false);
    dialog.setWindowTitle("Log file");
    dialog.setFilter("CSV (*.csv)");
    dialog.setDirectory(".");
    dialog.setAcceptMode(QFileDialog::AcceptSave);
    dialog.setFileMode(QFileDialog::AnyFile);

    QString file;
    if (dialog.exec())
        file = dialog.selectedFiles().first();
    else
        return;

    m_txt_log_file->setText(file);
}

void SettingsDialog::logChanged(const QString &file)
{
    QFileInfo file_info(file);
    bool valid = file_info.isFile();
    m_txt_log_file->setStyleSheet(valid ? "color: green;" : "color: red;");
    m_txt_log_file->setToolTip(file);
}
